﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Foundation.Core;

namespace Dyao.Book.Core
{
    public static class ClaimsIdentityExtensions
    {
        //
        // 摘要:
        //     Find user id by claims principal
        //
        // 参数:
        //   principal:
        //     claims principal
        public static string FindUserId(this ClaimsPrincipal principal)
        {
            Assert.NotNull(principal, "principal");
            Claim claim = principal.Claims?.FirstOrDefault((Claim c) => c.Type == DataClaimTypes.UserId);
            if (claim == null || claim.Value.IsNullOrWhiteSpace())
            {
                return null;
            }

            return claim.Value;
        }

        //
        // 摘要:
        //     Find user id by IIdentity
        //
        // 参数:
        //   identity:
        //     identity
        public static string FindUserId(this IIdentity identity)
        {
            Assert.NotNull(identity, "identity");
            return ((identity as ClaimsIdentity)?.Claims?.FirstOrDefault((Claim c) => c.Type == DataClaimTypes.UserId)).Value;
        }

        //
        // 摘要:
        //     Find username by claims principal
        //
        // 参数:
        //   principal:
        //     claims principal
        public static string FindUserName(this ClaimsPrincipal principal)
        {
            Assert.NotNull(principal, "principal");
            Claim claim = principal.Claims?.FirstOrDefault((Claim c) => c.Type == DataClaimTypes.UserName);
            if (claim == null || claim.Value.IsNullOrWhiteSpace())
            {
                return null;
            }

            return claim.Value;
        }

        //
        // 摘要:
        //     Find client id by claims principal
        //
        // 参数:
        //   principal:
        //     claims principal
        public static string FindClientId(this ClaimsPrincipal principal)
        {
            Assert.NotNull(principal, "principal");
            Claim claim = principal.Claims?.FirstOrDefault((Claim c) => c.Type == DataClaimTypes.ClientId);
            if (claim == null || claim.Value.IsNullOrWhiteSpace())
            {
                return null;
            }

            return claim.Value;
        }

        //
        // 摘要:
        //     Find client id by IIdentity
        //
        // 参数:
        //   identity:
        //     identity
        public static string FindClientId(this IIdentity identity)
        {
            Assert.NotNull(identity, "identity");
            Claim claim = (identity as ClaimsIdentity)?.Claims?.FirstOrDefault((Claim c) => c.Type == DataClaimTypes.ClientId);
            if (claim == null || claim.Value.IsNullOrWhiteSpace())
            {
                return null;
            }

            return claim.Value;
        }
    }
}
